﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

using ProcessIoUtil;

namespace ProcessIoTest
{
    public partial class Form1 : Form
    {
        private ProcessIoWrapper wrapper = null;

        public Form1()
        {
            InitializeComponent();
        }

        public void Log(RichTextBox box, string text)
        {
            box.AppendText(text);
            box.SelectionStart = box.Text.Length;
            box.ScrollToCaret();
        }

        public void UpdateUI(bool isProcessRunning)
        {
            button1.Enabled = !isProcessRunning;
            button2.Enabled = isProcessRunning;
            button3.Enabled = isProcessRunning;
            textBox3.Enabled = isProcessRunning;
        }

        public void LogOutput(string text)
        {
            // this function would be called in another thread
            Invoke((Action)(() => { Log(richTextBox1, text); }));
        }

        public void LogError(string text)
        {
            Invoke((Action)(() => { Log(richTextBox2, text); }));
        }

        public void WhenProcessExited()
        {
            Invoke((Action)(() => { UpdateUI(false); }));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            UpdateUI(false);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!button1.Enabled || textBox1.Text.Trim().Length <= 0) return;

            if (wrapper != null)
            {
                wrapper.Dispose();
                wrapper = null;
                Thread.Sleep(100);
            }

            wrapper = new ProcessIoWrapper(textBox1.Text.Trim(), textBox2.Text.Trim());
            wrapper.OnStandardOutputTextRead = new Action<string>((text) => { LogOutput(text); });
            wrapper.OnStandardErrorTextRead = new Action<string>((text) => { LogError(text); });
            wrapper.OnProcessExited = new Action(() => { WhenProcessExited(); });
            wrapper.StartProcess();

            UpdateUI(true);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (wrapper == null) return;
            wrapper.Dispose();
            wrapper = null;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (!textBox3.Enabled || textBox3.Text.Trim().Length <= 0) return;
            if (wrapper != null)
            {
                wrapper.WriteStandardInput(textBox3.Text.Trim() + "\n");
                textBox3.Text = "";
            }
        }
    }
}
